package o2o.web.actions.shop;

import o2o.config.dao.UserDaoSql;
import com.jinyou.utils.common.*;
import o2o.cache.shop.ShopMemory;
import o2o.cache.shop.ShopWalletMemory;
import o2o.cache.shop.ShopWalletPopMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.cache.wallet.UserWalletMemory;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.common.UserType;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.shop.ShopWallet;
import o2o.dao.PO.shop.ShopWalletPop;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.wallet.PAY_TYPE;
import o2o.dao.PO.wallet.UserWallet;
import o2o.dao.VO.shop.ShopInfoVO;
import o2o.web.actions.user.User;
import o2o.web.actions.wallet.UserWalletMan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import o2o.system.data.SYS_SETTINGS;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//商铺钱包
//--------------------------------------------------------已废弃
@Controller
public class ShopWalletAction {

    //获取钱包余额
    @RequestMapping(method = RequestMethod.POST, value = "/shop/wallet1")
    @ResponseBody
    public String shop_wallet(String token) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.getInstance().hasShopAuth(user.getUsername(),user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (null == shopInfo) {
            return AjaxResult.errorResult("未查询到您的信息");
        }


//        ShopWallet shopWallet = ShopWalletMemory.getInstance().getShopWallet(user.getUsername());
//        if (null == shopWallet) {
//            shopWallet = new ShopWallet();
//            shopWallet.setMoney(0d);
//        }
//
//        //每月提现次数限制
//        SysSetting sysSettingMonth = SysSettingMemory.getInstance().getByName(SysSettingKey.MONEY_POP_TIMES);
//        if (null != sysSettingMonth) {
//            shopWallet.setMonthPopTimes(sysSettingMonth.getVal());
//        }
//        //每周提现次数
//        SysSetting sysSettingWeek = SysSettingMemory.getInstance().getByName(SysSettingKey.SHOP_WALLET_POP_WEEK);
//        if (null != sysSettingWeek) {
//            shopWallet.setWeekPopTimes(sysSettingWeek.getVal());
//        }
//        //每月提现金额限制
//        SysSetting sysSettingMoney = SysSettingMemory.getInstance().getByName(SysSettingKey.SHOP_WALLET_POP_MONEY);
//        if (null != sysSettingMoney) {
//            shopWallet.setPopOneMoney(sysSettingMoney.getVal());
//        }
//
//        return AjaxResult.successResult(shopWallet);


        UserWallet userWallet = UserWalletMemory.getInstance().getWallet(user.getUsername());
        if (null == userWallet) {
            userWallet = new UserWallet();
            userWallet.setMoney(0d);
        }

        //每月提现次数限制
//        SysSetting sysSettingMonth = SysSettingMemory.getInstance().getByName(SysSettingKey.MONEY_POP_TIMES);
//        if (null != sysSettingMonth) {
//            userWallet.setMonthPopTimes(sysSettingMonth.getVal());
//        }
//        //每周提现次数
//        SysSetting sysSettingWeek = SysSettingMemory.getInstance().getByName(SysSettingKey.SHOP_WALLET_POP_WEEK);
//        if (null != sysSettingWeek) {
//            userWallet.setWeekPopTimes(sysSettingWeek.getVal());
//        }
//        //每月提现金额限制
//        SysSetting sysSettingMoney = SysSettingMemory.getInstance().getByName(SysSettingKey.SHOP_WALLET_POP_MONEY);
//        if (null != sysSettingMoney) {
//            userWallet.setPopOneMoney(sysSettingMoney.getVal());
//        }


        //每月提现次数
        if (null == SYS_SETTINGS.SHOP_WALLET_POP_MONEY) {
            userWallet.setMonthPopTimes(0);
        } else {
            userWallet.setMonthPopTimes(SYS_SETTINGS.SHOP_WALLET_POP_MONEY);
        }

        //商户每周提现次数限制
        if (null == SYS_SETTINGS.SHOP_WALLET_POP_WEEK) {
            userWallet.setWeekPopTimes(0);
        } else {
            userWallet.setWeekPopTimes(SYS_SETTINGS.SHOP_WALLET_POP_WEEK);
        }

        //单次提现限额
        if (null == SYS_SETTINGS.MONEY_POP_TIMES) {
            userWallet.setPopOneMoney(0);
        } else {
            userWallet.setPopOneMoney(SYS_SETTINGS.MONEY_POP_TIMES);
        }


        return AjaxResult.successResult(userWallet);
    }


    //绑定支付渠道
    @RequestMapping(method = RequestMethod.POST, value = "/shop/wallet/bind1")
    @ResponseBody
    public String shop_wallet_pop(String token, String alipay, String alipayRealName, String tenpay, String tenpayopenId, String tenpayRealName) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.getInstance().hasShopAuth(user.getUsername(),user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (null == shopInfo) {
            return AjaxResult.errorResult("未查询到您的信息");
        }

        boolean isHas = false;
        ShopWallet shopWallet = ShopWalletMemory.getInstance().getShopWallet(user.getUsername());
        if (null == shopWallet) {//没有新建
            shopWallet = new ShopWallet();
            shopWallet.setShopUsername(user.getUsername());
            shopWallet.setShopId(shopInfo.getId());
        } else {
            isHas = true;
        }


        boolean inputRight = false;
        //支付宝信息
        if (ValidateUtil.isNotNull(alipay) && ValidateUtil.isNotNull(alipayRealName)) {
            shopWallet.setAlipay(alipay);
            shopWallet.setAlipayRealName(alipayRealName);

            inputRight = true;
        }
        //微信信息
        if (ValidateUtil.isNotNull(tenpay) && ValidateUtil.isNotNull(tenpayRealName)) {
            shopWallet.setTenpay(tenpay);
            if (ValidateUtil.isNotNull(tenpayopenId)) {
                shopWallet.setTenpayopenId(tenpayopenId);
            }
            shopWallet.setTenpayRealName(tenpayRealName);

            inputRight = true;
        }

        if (!inputRight) {
            return AjaxResult.errorResult("请填写完整");
        }

        //保存到数据库
        if (isHas) {//更新数据库
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.ShopWallet).append(" set alipay='").append(shopWallet.getAlipay())
                    .append("',alipayRealName='").append(shopWallet.getAlipayRealName()).append("',tenpay='").append(shopWallet.getTenpay())
                    .append("',tenpayRealName='").append(shopWallet.getTenpayRealName()).append("',tenpayopenId='").append(shopWallet.getTenpayopenId())
                    .append("',updateUser='").append(user.getUsername()).append("' where shopUsername='").append(user.getUsername()).append("' and delFlag = 0 ");
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("绑定失败，请稍后再试");
            }

        } else {//新建一条
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.ShopWallet, shopWallet);
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("绑定失败，请稍后再试");
            }
        }

        //在缓存中修改
        ShopWalletMemory.getInstance().updateShopWallet(user.getUsername());

        return AjaxResult.successResult();
    }


    //提现申请
    @RequestMapping(method = RequestMethod.POST, value = "/shop/wallet/pop1")
    @ResponseBody
    public String shop_wallet_pop(String token, Double money, String channel) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.getInstance().hasShopAuth(user.getUsername(),user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        ShopInfo shopInfo = ShopMemory.getInstance().getShopByUsername(user.getUsername());
        if (null == shopInfo) {
            return AjaxResult.errorResult("未查询到您的信息");
        }

        if (ValidateUtil.isNotAbsDouble(money)) {
            return AjaxResult.errorResult("请输入正确的提现金额");
        }


//        if (money < 200) {
//            return AjaxResult.errorResult("提现金额不少于200");
//        }

        ShopWallet shopWallet = ShopWalletMemory.getInstance().getShopWallet(user.getUsername());
        if (null == shopWallet) {
            return AjaxResult.errorResult("未查询到正确的余额");
        }
        if (JYMathDoubleUtils.sub(shopWallet.getMoney(), money) < 0) {
            return AjaxResult.errorResult("您的提现额度已超出余额");
        }

        //查询本月已提现次数
        //select count(1) times from shop_wallet_pop  where shopUsername = '15628986552'  and FROM_UNIXTIME(ifnull(popTime,0)/1000,'%Y%m') = DATE_FORMAT(NOW(),'%Y%m')
        StringBuffer sb = new StringBuffer();
        sb.append("select count(1) times from ").append(PojoTables.ShopWalletPop).append(" where shopUsername = '").append(user.getUsername())
                .append("' and FROM_UNIXTIME(ifnull(createTime,0)/1000,'%Y%m') = DATE_FORMAT(NOW(),'%Y%m')");
        HashMap<String, Object> hashMap = null;
        try {
            hashMap = UserDaoSql.getInstance().queryMapBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询您本月提现次数时出错，请稍后再试");
        }
        if (null == hashMap) {
            return AjaxResult.errorResult("查询您本月提现次数时出错，请稍后再试");
        }
        try {
            Long times = (Long) hashMap.get("times");
            if (null == times) {
                return AjaxResult.errorResult("查询您本月提现次数时出错，请稍后再试");
            }
//            if (times > 0) {
            //每月提现次数限制
//                SysSetting sysSettingMonth = SysSettingMemory.getInstance().getByName(SysSettingKey.MONEY_POP_TIMES);
//                if (null != sysSettingMonth && sysSettingMonth.getVal() > 0) {
//                    if (times >= sysSettingMonth.getVal()) {
//                        return AjaxResult.errorResult("您本月的提现次数（" + sysSettingMonth.getVal() + "次）已用完，请下月再来");
//                    }
//                }
            if (null == SYS_SETTINGS.MONEY_POP_TIMES) {
                if (times >= SYS_SETTINGS.MONEY_POP_TIMES) {
                    return AjaxResult.errorResult("您本月的提现次数（" + SYS_SETTINGS.MONEY_POP_TIMES + "次）已用完，请下月再来");
                }
            }

//            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("查询您本月提现次数时出错，请稍后再试");
        }


        if (ValidateUtil.isNull(channel)) {
            return AjaxResult.errorResult("请选择提现到位置");
        }


        ShopWalletPop shopWalletPop = new ShopWalletPop();
        switch (channel) {
            case PAY_TYPE.ALLIPAY: {//支付宝
                if (ValidateUtil.isNull(shopWallet.getAlipay()) || ValidateUtil.isNull(shopWallet.getAlipayRealName())) {
                    return AjaxResult.errorResult("您的支付宝信息不完整，不允许提现");
                }
                shopWalletPop.setAlipay(shopWallet.getAlipay());
                shopWalletPop.setAlipayRealName(shopWallet.getAlipayRealName());
            }
            break;
            case PAY_TYPE.WX: {//微信
                if (ValidateUtil.isNull(shopWallet.getTenpay()) || ValidateUtil.isNull(shopWallet.getTenpayRealName())) {
                    return AjaxResult.errorResult("您的微信账号信息不完整，不允许提现");
                }
                shopWalletPop.setTenpay(shopWallet.getTenpay());
                shopWalletPop.setTenpayopenId(shopWallet.getTenpayopenId());
                shopWalletPop.setTenpayRealName(shopWallet.getTenpayRealName());
            }
            break;
            default: {
                return AjaxResult.errorResult("请选择提现到位置.");
            }
        }
        Long time = DateUtils.getCurrTime();
        shopWalletPop.setShopId(shopWallet.getShopId());
        shopWalletPop.setShopUsername(shopWallet.getShopUsername());
        shopWalletPop.setMoney(money);
        shopWalletPop.setChannel(channel);
        shopWalletPop.setIsDone(0);
        shopWalletPop.setDelFlag(0);
        shopWalletPop.setCreateTime(time);
        shopWalletPop.setCreateUser(user.getUsername());

        //插入数据库
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.ShopWalletPop, shopWalletPop);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("申请失败，请稍后再试");
        }

        //更新缓存
        ShopWalletPopMemory.getInstance().updateShopWalletPop(user.getUsername());

//        //更新余额
//        ResultInfo resultInfo = ShopWalletMan.saveOrUpdateShopWallet(user.getUsername(), shopInfo.getId(), ShopWalletMan.POP, money, user.getUsername());
//        if (!resultInfo.isSuccess()) {
//            return AjaxResult.errorResult(resultInfo.getError());
//        }

        //更新余额
        ResultInfo resultInfo = UserWalletMan.saveOrUpdateUserWallet(user.getUsername(), UserType.SHOP_OWNER, shopInfo.getId(), ShopWalletMan.POP, money, 0d, user.getUsername());
        if (!resultInfo.isSuccess()) {
            return AjaxResult.errorResult(resultInfo.getError());
        }


        return AjaxResult.successResult();
    }


    //查看自己的提现申请记录
    @RequestMapping(method = RequestMethod.POST, value = "/shop/wallet/pop/history1")
    @ResponseBody
    public String shop_wallet_pop_history(String token, Long createTim, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.getInstance().hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        //
        List<ShopWalletPop> list = ShopWalletPopMemory.getInstance().getShopWalletPop(user.getUsername());

        Boolean flag = false;//需不需要判断时间戳
        if (null != createTim && createTim > 0) {
            flag = true;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }

        if (null != list && list.size() > 0) {
            List<ShopWalletPop> resultList = new ArrayList<ShopWalletPop>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                if (flag) {//需要判断时间戳
                    if (list.get(i).getCreateTime() < createTim) {
                        resultList.add(list.get(i));
                    }
                } else {
                    resultList.add(list.get(i));
                }
            }
            //排序订单，返回前size条
            resultList = sort(resultList);
            List<ShopWalletPop> reList = new ArrayList<ShopWalletPop>();
            for (int i = 0; i < resultList.size(); i++) {
                if (null == resultList.get(i)) {
                    continue;
                }
                if (i < size) {
                    reList.add(resultList.get(i));
                }
            }
            if (ValidateUtil.isAbsList(reList)) {
                return AjaxResult.successResult(reList.size(), list);
            }
        }
        return AjaxResult.successResult(0, null);
    }

    //排序
    private List<ShopWalletPop> sort(List<ShopWalletPop> list) {
        JYListSort.sortDesc(list, "createTime");
        return list;
    }

    //查询所有店铺的提现申请记录
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/pop/history1")
    @ResponseBody
    public String shop_wallet_pop_history_admin(String token, String username, Integer isDone, Integer page, Integer size) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.getInstance().hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        List<ShopWalletPop> list = null;
        if (ValidateUtil.isNotNull(username)) {//查看某一用户的
            if (ValidateUtil.isAbsInteger(isDone) && isDone > 0) {
                List<ShopWalletPop> listTemp = ShopWalletPopMemory.getInstance().getShopWalletPop(username);
                if (ValidateUtil.isAbsList(listTemp)) {
                    list = new ArrayList<ShopWalletPop>();
                    if (ValidateUtil.isAbsInteger(isDone) && isDone > 0) {
                        for (int i = 0; i < listTemp.size(); i++) {
                            if (null == listTemp.get(i)) {
                                continue;
                            }
                            if (0 == 1 - isDone && 0 == 1 - listTemp.get(i).getIsDone()) {//1已提现
                                list.add(listTemp.get(i));
                            } else if (0 == 2 - isDone && 0 == 0 - listTemp.get(i).getIsDone()) {//2未提现
                                list.add(listTemp.get(i));
                            }
                        }
                    }
                }
            } else {
                list = ShopWalletPopMemory.getInstance().getShopWalletPop(username);
            }
        } else {
            //所有用户的
            //isDone  0所有 1已提现  2所有未提现
            if (ValidateUtil.isAbsInteger(isDone) && isDone > 0) {
                if (0 == 1 - isDone) {
                    list = ShopWalletPopMemory.getInstance().getAllShopWalletPop(true);
                } else if (0 == 2 - isDone) {
                    list = ShopWalletPopMemory.getInstance().getAllShopWalletPop(false);
                }
            } else {//所有的
                list = ShopWalletPopMemory.getInstance().getAllShopWalletPop();
            }


        }

        JYPageUtils.PageList pageList = JYPageUtils.getList(list, page, size);
        if (null != pageList && null != pageList.list && pageList.list.size() > 0) {
            List<ShopWalletPop> resultList = new ArrayList<ShopWalletPop>();
            for (int i = 0; i < pageList.list.size(); i++) {
                ShopWalletPop shopWalletPop = (ShopWalletPop) pageList.list.get(i);
                if (null == shopWalletPop) {
                    continue;
                }
                ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopWalletPop.getShopId());
                ShopInfoVO shopInfoVO = new ShopInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(shopInfo, shopInfoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                shopWalletPop.setShopInfo(shopInfoVO);

                resultList.add(shopWalletPop);
            }

            return AjaxResult.successResult(pageList.totalCount, resultList.size(), resultList);
        }


        return AjaxResult.successResult(0, 0, null);
    }

    //管理员设置为已提现
    @RequestMapping(method = RequestMethod.POST, value = "/admin/shop/pop/done1")
    @ResponseBody
    public String shop_wallet_pop_done_admin(String token, String username, Long id) {
        if (1 == 1) {
            return AjaxResult.errorResult("您使用的当前版本已停用，请联系开发者");
        }

        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //验证是否有登录权限
        if (!User.getInstance().hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }

        if (ValidateUtil.isNotID(id)) {
            return AjaxResult.errorResult("请选择需要为已提现的记录");
        }

        if (ValidateUtil.isNull(username)) {
            return AjaxResult.errorResult("请选择工人账号");
        }

        List<ShopWalletPop> list = ShopWalletPopMemory.getInstance().getShopWalletPop(username);

        if (!ValidateUtil.isAbsList(list)) {
            return AjaxResult.errorResult("未找到该用户对应的提现信息");
        }
        boolean isHas = false;
        Double money = 0d;
        for (int i = 0; i < list.size(); i++) {
            if (null == list.get(i)) {
                continue;
            }
            if (ValidateUtil.isNull(list.get(i).getShopUsername())) {
                continue;
            }
            if (0 == id - list.get(i).getId()) {
                if (0 == 1 - list.get(i).getIsDone()) {
                    return AjaxResult.errorResult("当前已提现，请勿重复操作");
                }
                isHas = true;
                money = list.get(i).getMoney();
                break;
            }
        }

        if (isHas) {
            //设置为已提现
            Long time = DateUtils.getCurrTime();
            StringBuilder sb = new StringBuilder();
            sb.append("update ").append(PojoTables.ShopWalletPop).append(" set isDone = 1,updateUser = '").append(user.getUsername())
                    .append("',popTime = ").append(time).append(" where id =").append(id).append(" and shopUsername = '").append(username).append("' and isDone = 0 and delFlag = 0");
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("设置失败，请稍后再试");
            }

            //更新缓存
            ShopWalletPopMemory.getInstance().updateShopWalletPop(username);


            //更新用户账号余额信息
            ShopWalletMan.saveOrUpdateShopWallet(username, null, ShopWalletMan.POP_SUCCESS, money, user.getUsername());
//            ShopWalletMan.saveOrUpdateShopWallet(username, null, ShopWalletMan.POP_SUCCESS, money, user.getUsername());

        } else {
            return AjaxResult.errorResult("未找到相对应的提现申请记录");
        }

        return AjaxResult.successResult();
    }

}
